package com.lvmama.rhino.service.impl.comment;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lvmama.rhino.mapperComment.ProductAnalysisMapper;
import com.lvmama.rhino.pojo.comment.Enum.EnumForCategory;
import com.lvmama.rhino.pojo.comment.Enum.EnumForComment;
import com.lvmama.rhino.pojo.comment.Enum.MonthEnum;
import com.lvmama.rhino.pojo.comment.entity.CommentTendency;
import com.lvmama.rhino.pojo.comment.entity.ProductCommentAnalysis;
import com.lvmama.rhino.pojo.comment.entity.ProductViewPointRankData;
import com.lvmama.rhino.pojo.comment.query.CommentTendencyQuery;
import com.lvmama.rhino.pojo.comment.query.ProductRankPageQuery;
import com.lvmama.rhino.pojo.comment.query.ProductViewPointRankQuery;
import com.lvmama.rhino.pojo.comment.response.CommentTendencyResponse;
import com.lvmama.rhino.pojo.comment.response.ProductViewPointRankResponse;
import com.lvmama.rhino.pojo.comment.vo.BarAddIdData;
import com.lvmama.rhino.service.comment.ProductAnalysisService;
import com.lvmama.rhino.utils.Constants;
import com.lvmama.rhino.utils.DateUtil;
import com.lvmama.rhino.utils.StringTools;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 产品评价分析
 */
@Service("productAnalysisService")
@Transactional
public class ProductAnalysisServiceImpl implements ProductAnalysisService {

    private Logger log = Logger.getLogger(ProductAnalysisServiceImpl.class);
    @Autowired
    private ProductAnalysisMapper productAnalysisMapper;

    @Override
    public List<ProductCommentAnalysis> getProductList(
            ProductCommentAnalysis productCommentList) {

        List<ProductCommentAnalysis> productList = productAnalysisMapper
                .getProductList();
        for (ProductCommentAnalysis productCommentAnalysis : productList) {
            productCommentAnalysis.setCategoryName(EnumForCategory.
                    getCategoryShowName(productCommentAnalysis.getCategoryId()));
        }
        return productList;
    }

    /**
     * 评价分析分页查询
     *
     * @param query 请求参数
     * @return 分页
     */
    @Override
    public PageInfo<ProductCommentAnalysis> getProductRankPage(ProductRankPageQuery query) {
        log.info("getProductRankPage start. query:" + query);
        //设置分页
        PageHelper.startPage(query.getCurrentPage(), query.getPageSize());
        PageInfo<ProductCommentAnalysis> pageInfo = null;
        try {
            List<ProductCommentAnalysis> productRanks = productAnalysisMapper.getProductRankPage(query);
            for (ProductCommentAnalysis productRank : productRanks) {
                String categoryName = Constants.UNKNOWN;
                String categoryId = productRank.getCategoryId();
                if (!Constants.UNKNOWNDATA.equals(categoryId)) {
                    categoryName = StringUtils.isNotBlank(categoryId) ? EnumForCategory.getCategoryShowName(categoryId) : null;
                    if (StringUtils.isBlank(categoryName)) {
                        categoryName = EnumForCategory.getCategoryName(categoryId);
                    }
                }
                productRank.setCategoryName(categoryName);

                // 产品名称
                String name = productRank.getProductName();
                if (StringUtils.isBlank(name)) {
                    name = Constants.UNKNOWN;
                } else if (Constants.UNKNOWNDATA.equals(name.trim()) ||
                        Constants.UNKNOWNDATA2.equals(name.trim()) ||
                        Constants.UNKNOWNDATA3.equalsIgnoreCase(name.trim())) {
                    name = Constants.UNKNOWN;
                }
                productRank.setProductName(name);
                productRank.setProductShortName(productRank.getProductName());

                // 检查好中差评计算准确性
                double good = StringTools.checkCommentRate(productRank.getGood(), productRank.getBad(), productRank.getMedium());
                productRank.setGood(good);
            }
            pageInfo = new PageInfo<>(productRanks);
        } catch (Exception e) {
            log.info("getProductRankPage error:" + e.getMessage(), e);
        }
        log.info("getProductRankPage end.");
        return pageInfo;
    }

    /**
     * 查询产品点评趋势
     *
     * @param query 查询条件
     * @return 结果集
     */
    @Override
    public List<CommentTendency> selectProductCommentTendency(CommentTendencyQuery query) {
        log.info("selectProductCommentTendency start.");
        List<CommentTendency> result = null;
        try {
            result = productAnalysisMapper.selectProductCommentTendency(query);
            if (null == result) {
                return null;
            }
        } catch (Exception e) {
            log.error("selectProductCommentTendency error:" + e.getMessage(), e);
        }
        log.info("selectProductCommentTendency end.");
        return result;
    }

    /**
     * 查询产品当年点评趋势
     *
     * @param productId 产品id
     * @return 结果集
     */
    @Override
    public List<CommentTendencyResponse> selectProductCurrentYearCommentTendency(String productId) {
        log.info("selectProductCommentTendency start.");
        List<CommentTendencyResponse> result = new ArrayList<>();
        try {
            CommentTendencyQuery query = new CommentTendencyQuery();
            query.setDays(365);
            query.setProductId(productId);
            List<CommentTendency> tendencies = selectProductCommentTendency(query);

            if (null == tendencies || tendencies.isEmpty()) {
                return null;
            }
            //把没有的月份补0
            for (MonthEnum month : MonthEnum.values()) {
                //好评
                CommentTendency positive = new CommentTendency();
                positive.setMonth(DateUtil.getCurrentYear() + "-" + month.getCode());
                positive.setType(EnumForComment.positive.getShowName());
                if (!tendencies.contains(positive)) {
                    CommentTendencyResponse response = new CommentTendencyResponse();
                    response.setType(positive.getType());
                    response.setMonth(month.getName());
                    response.setComment(0F);
                    result.add(response);
                }
                //中评
                CommentTendency moderate = new CommentTendency();
                moderate.setMonth(DateUtil.getCurrentYear() + "-" + month.getCode());
                moderate.setType(EnumForComment.neuter.getShowName());
                if (!tendencies.contains(moderate)) {
                    CommentTendencyResponse response = new CommentTendencyResponse();
                    response.setMonth(month.getName());
                    response.setType(moderate.getType());
                    response.setComment(0F);
                    result.add(response);
                }
                //差评
                CommentTendency negative = new CommentTendency();
                negative.setMonth(DateUtil.getCurrentYear() + "-" + month.getCode());
                negative.setType(EnumForComment.negative.getShowName());
                if (!tendencies.contains(negative)) {
                    CommentTendencyResponse response = new CommentTendencyResponse();
                    response.setMonth(month.getName());
                    response.setComment(0F);
                    response.setType(negative.getType());
                    result.add(response);
                }
            }
            //把查询结果添加到result
            for (CommentTendency tendency : tendencies) {
                CommentTendencyResponse response = new CommentTendencyResponse();
                String monthCode = tendency.getMonth().split("-")[1];
                response.setMonth(MonthEnum.getEnum(monthCode).getName());
                response.setComment(tendency.getRate());
                response.setType(tendency.getType());
                result.add(response);
            }
        } catch (Exception e) {
            log.error("selectProductCommentTendency error:" + e.getMessage(), e);
        }
        log.info("selectProductCommentTendency end.");
        return result;
    }

    /**
     * 查询产品的热词排行
     *
     * @param query 查询条件
     * @return 结果集
     */
    @Override
    public ProductViewPointRankResponse selectProductViewPointRank(ProductViewPointRankQuery query) {
        log.info("selectProductViewPointRank start, query:" + query);
        ProductViewPointRankResponse response = new ProductViewPointRankResponse();
        try {
            //依次查询好中差评数据
            for (EnumForComment comment : EnumForComment.values()) {
                query.setCommentType(comment.getValue());
                List<ProductViewPointRankData> rankDataList = productAnalysisMapper
                        .selectProductViewPointRank(query);
                if (comment.getValue() == EnumForComment.positive.getValue()) {
                    response.setPositive(rankDataList);
                }
                if (comment.getValue() == EnumForComment.neuter.getValue()) {
                    response.setModerate(rankDataList);
                }
                if (comment.getValue() == EnumForComment.negative.getValue()) {
                    response.setNegative(rankDataList);
                }
            }
        } catch (Exception e) {
            log.error("selectProductViewPointRank error:" + e.getMessage(), e);
        }
        log.info("selectProductViewPointRank end.");
        return response;
    }

    @Override
    public JSONArray getProductSortRank(ProductRankPageQuery query) {
        log.info("getProductSortRank start. query:" + query);
        JSONArray barData = new JSONArray();
        //设置分页
        try {
            PageHelper.startPage(query.getCurrentPage(), query.getPageSize());
            List<ProductCommentAnalysis> productRanks = productAnalysisMapper.getProductSortRank(query);
            PageInfo<ProductCommentAnalysis> productInfo = new PageInfo<>(productRanks);
            List<BarAddIdData> barList = new ArrayList<>();
            if (null != productInfo && !CollectionUtils.isEmpty(productInfo.getList())) {
                int j = 1;
                for(int i = 0; i < productInfo.getList().size(); i++) {
                    ProductCommentAnalysis comment = productInfo.getList().get(i);
                    BarAddIdData vo = new BarAddIdData();
                    vo.setId(Long.parseLong(comment.getProductId()));
                    String name = comment.getProductName();

                    if (StringUtils.isBlank(name)) {
                        name = Constants.UNKNOWN + String.valueOf(j++);
                    } else if (Constants.UNKNOWNDATA.equals(name.trim()) ||
                            Constants.UNKNOWNDATA2.equals(name.trim()) ||
                            Constants.UNKNOWNDATA3.equalsIgnoreCase(name.trim())) {
                        name = Constants.UNKNOWN + String.valueOf(j++);
                    }
                    vo.setName(name);
                    vo.setValue(comment.getProductCommentCount());
                    barList.add(vo);
                }
            }
            barData = JSONArray.fromObject(barList);
        } catch (Exception e) {
            log.info("getProductSortRank error:" + e.getMessage(), e);
        }
        log.info("getProductSortRank end.");
        return barData;
    }

}
